const express = require('express');
const router = express.Router();
const utils = require('../../utils');

const filters = [
    {
        Name: 'title',
        Type: 'String',
    },
    {
        Name: 'content',
        Type: 'String',
    },
];

// global search
router.get('/',
    (req, res, next) => {
        // type
        const qType = {};

        if (req.query.type === 'all') {
            //
        } else if (req.query.type){
            qType.__type = req.query.type;
        }

        // query
        res.locals.filter = Object.assign(
            {}, 
            res.app.modules['input-field'].generateQueryFilter(filters, req.query), 
            res.locals.filter, 
            utils.makeQueryFilters(req, 'search'),
            qType, 
        );

        res.locals.fields = [
            '__oid',
            '__type',

            "id",
            "LastUpdateDate",
            "date",
            "title",
            "content",
            "图片",

            // "标题",
            // "时间",

            // "详情",
            "类型",
            "等级",
            // "日期",
            "领域",

            // "名称",
            // "发布日",
            // "实施日",
            // "废止日",
            "子库",
            "来源",
            "格式",
            // "大小",
            // "描述",
            
            // "姓名",
            // "别名",
            "类别",
            // "单位",
            // "职位",
            // "联系方式",
            "行业",
            'label',
        ];
        res.locals.options = {
            sort: { date: 'desc' },
            lean: true
        };

        return next();
    },
    router.FindDocuments('sq_portal', false, async (req, res) => {
        if(!res.locals.data || !res.locals.data.total) return;

        for (let i = 0; i < res.locals.data.docs.length; i += 1) {
            const doc = res.locals.data.docs[i];

            doc.content = utils.repalceHtmlToText(doc.content || '');
            doc.type = doc.__type;
            doc.id = doc.__oid;
            delete doc.__type;
            delete doc.__oid;
        }

        await utils.getDictLabel(req, res, '领域', '领域列表', true);
    })
);

module.exports = router;
